<template>
	<view>
		<view class="ls2 header">
			<view class="gray fs28">支付金额</view>
			<view class="mt-1">¥{{total}}</view>
		</view>

		<view class="center ml-3 font-base">
			<view class="d-flex bb mt-3">
				<image src="@/static/img/cate/Wechat.png" mode="widthFix" style="width: 62rpx;height: 54rpx;" />
				<view class="d-flex ml-3 flex-column flex-1 ">
					<view class="">微信支付</view>
					<view class="gray fs28">推荐使用微信支付</view>
				</view>
				<image class="m-3"
					:src="payType == 1?'/static/img/cate/Selected.png':'/static/img/cate/Notselected.png'"
					mode="widthFix" style="width: 40rpx;" @click="changePayType(1)"></image>
			</view>
			<!-- <view class="d-flex bb mt-3">
				<image src="@/static/img/cate/Alipay.png" mode="widthFix" style="width: 62rpx;height: 54rpx;" />
				<view class="d-flex ml-3 flex-column flex-1">
					<view class="">支付宝支付</view>
					
				</view>
				<image class="m-3"
					:src="payType == 2?'/static/img/cate/Selected.png':'/static/img/cate/Notselected.png'"
					mode="widthFix" style="width: 40rpx;" @click="changePayType(2)"></image>
			</view> -->
		</view>
		<button @tap="confirm">确认支付</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				payType: 1,
				tag: '',
				isPay: true,
				total: 0.00,
			};
		},
		onLoad(options) {
			if (options.money > 0) {
				this.total = options.money
				uni.setStorageSync('total', options.money);
			} else {
				this.total = uni.getStorageSync('total');
			}

			this.tag = uni.getStorageSync('tag')

			// #ifdef H5
			if (this.$wechat && this.$wechat.isWechat()) {
				this.isWechat = true;

				//微信公众号登录
				if (!this.openId) {
					if (window.location.href.indexOf('?code=') !== -1 || window.location.href.indexOf('&code=') !== -1) {
						this.isPay = false;
						let code;
						if (window.location.href.indexOf('?code=') !== -1) {
							code = window.location.href.split('?code=')[1].split('&')[0];
						} else {
							code = window.location.href.split('&code=')[1].split('&')[0];
						}
						//请求后端网络请求
						this.getWxOpenId(code);
					}
				}
			}
			// #endif

			// #ifdef MP-WEIXIN
			this.isWechat = true;
			// #endif
		},
		methods: {
			//选择支付方式
			changePayType(type) {
				this.payType = type;
			},

			//确认支付
			confirm: async function() {
				let tag = this.tag
				if (!tag) {
					this.$api.msg('非法操作！');
					return false;
				}
				this.isPay = false

				let dataObj = {
					token: uni.getStorageSync('token'),
					tag: tag,
					paytype: this.payType
				}

				// #ifdef H5
				if (this.$wechat && this.$wechat.isWechat()) {
					//微信浏览器
					this.getAccessToken();
				} else {
					//非微信浏览器
					dataObj.type = 3;
					switch (this.payType) {
						case 1:
							this.wxPayH5(dataObj);
							break;
						case 2:
							let res = await this.$myRequest({
								url: '/goPay',
								data: dataObj,
								methods: 'POST',
							})

							let payInfo = res.data

							if (payInfo) {
								document.querySelector('.form').innerHTML = payInfo;
								document.forms[0].submit();
							}
							break;
					}
				}
				// #endif

				// #ifdef APP-PLUS
				dataObj.type = 4;
				console.log(dataObj)
				switch (this.payType) {
					case 1:
						this.wxPay(dataObj);
						break;
					case 2:
						this.aliPay(dataObj);
						break;
				}

				// #endif

				// #ifdef MP-WEIXIN
				var that = this
				uni.login({
					provider: "weixin",
					success(loginAuth) {
						that.getOpenId(loginAuth.code)
					}
				})

				// #endif
			},

			//支付宝支付
			async aliPay(dataObj) {
				uni.getProvider({ //获取可用的支付环境
					service: 'payment',
					success: res => {
						if (~res.provider.indexOf('alipay')) { //先判断用户是否有支付宝支付环境
							uni.showLoading({
								title: '正在调起支付宝支付'
							})

							uni.request({ //再从后端接口获取相关数据配置到orderInfo里，这个接口由后端配置好了，返回结果见下图1-支付宝
								url: this.$api.baseUrl + 'goPay',
								method: 'POST',
								data: dataObj,
								dataType: "json",
								success: res => {
									if (res.statusCode == 200) {
										if (res.data.status == 0) {
											this.$api.msg(res.data.msg);
											return false;
										}
										let payInfo = res
											.data //拿到后端返回数据后调用下面支付函数（若接口返回obj,需先转成string类型）
										uni.requestPayment({
											provider: 'alipay',
											orderInfo: payInfo, //支付宝订单数据（string类型）
											success: res => {
												uni.hideLoading();
												uni.redirectTo({
													url: '/pages/money/paySuccess'
												})
											},
											fail: err => {
												uni.hideLoading();
												this.$api.msg('支付失败！');
												this.isPay = true
											}
										});
									}
								},
								fail: () => {
									uni.hideLoading();
									this.$api.msg('服务器开小差了呢，请您稍后再试');
								}
							});
						} else {
							uni.showToast({
								title: '获取支付宝通道失败，请检查您的支付宝是否正常启用',
								icon: 'none'
							})
						}
					}
				});
			},

			//微信支付
			wxPay(dataObj) {
				uni.getProvider({
					service: 'payment',
					success: res => {
						if (~res.provider.indexOf('wxpay')) { //先判断用户是否有微信支付环境（是否安装了微信app）
							uni.showLoading({
								title: '正在调起微信支付'
							})
							console.log(this.$api.baseUrl)
							uni.request({
								url: this.$api.baseUrl + 'goPay',
								method: 'POST',
								data: dataObj,
								dataType: "json",
								success: (res) => {
									if (res.data.status == 4) {
										//（这里注意后端返回的数据类型是string还是object，需转成object类型）
										let resobj = res.data.data;
										let payInfo = JSON.parse(resobj)
										console.log(payInfo)
										uni.requestPayment({
											provider: 'wxpay',
											orderInfo: payInfo, //微信订单数据（Object类型）
											success: (res) => {
												uni.hideLoading();
												uni.redirectTo({
													url: '/pages/cart/PayCode'
												})
											},
											fail: (err) => {
												uni.hideLoading();
												console.log('fail:' + JSON.stringify(err));
												this.$api.msg('支付失败！');
												this.isPay = true
											}
										});
									} else if (res.data.status == 0) {
										this.$api.msg(res.data.msg);
									}
								},
								fail: (err) => {
									uni.hideLoading();
									this.$api.msg('服务器开小差了呢，请您稍后再试');
								}
							})
						} else {
							uni.showToast({
								title: '获取微信通道失败，请检查您的微信是否正常启用',
								icon: 'none'
							})
						}
					}
				});
			},
		},
	}
</script>

<style lang="scss">
	.header {
		margin: 80rpx auto;
		width: 100%;
		height: 100%;
		text-align: center;
		font-size: 38rpx;
	}

	.bb {
		// width: 100%;
		border-bottom: 2rpx solid #f5f5f5;
	}

	button {
		background-color: #e80909;
		color: white;
		border-radius: 20rpx;
		margin: 100rpx 20rpx;
	}
</style>
